package mws.task;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayedSwiftTask extends SwiftTask implements Delayed {

    private final long time;

    public DelayedSwiftTask(Runnable runnable, boolean quickPass,long delayTime, TimeUnit unit) {
        super(runnable, quickPass);
        time = System.nanoTime() + unit.toNanos(delayTime);

    }

    @Override
    public long getDelay(TimeUnit unit) {
        // 计算剩余延迟时间
        long remainingNanos = time - System.nanoTime();
        return unit.convert(remainingNanos, TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        // 空值检查
        if (other == null) {
            return 1; // 非空对象大于空对象
        }

        // 比较延迟时间
        long thisDelay = this.getDelay(TimeUnit.NANOSECONDS);
        long otherDelay = other.getDelay(TimeUnit.NANOSECONDS);

        // 使用Long.compare避免溢出问题
        return Long.compare(thisDelay, otherDelay);
    }
}
